package com.it.xyx;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Classname DemoController
 * @Description TODO
 * @Date 2024/8/22 15:24
 * @Created by 潜伏Sir
 */
@RestController
public class DemoController {

    @Resource
    DemoService demoService;

    @GetMapping("/demo")
    public String demo() {
        return "Hello World";
    }

    @GetMapping("/demo2")
    public String demo2() {
        return "Hello World2";
    }

    /**流控-链路演示demo
     * 3和4两个请求都访问flowLimitService.common()方法，阈值到达后对C限流，对D不管
     */

    @GetMapping("/demo3")
    public String demo3() {
        demoService.common();
        return "Hello World3";
    }


    @GetMapping("/demo4")
    public String demo4() {
        demoService.common();
        return "Hello World4";
    }

    @GetMapping("/rateLimit/byUrl")
    public String byUrl() {
        return "按rest地址限流测试OK";
    }


    @GetMapping("/rateLimit")
    //自定义限流返回
    @SentinelResource(value = "byResourceSentinelResource", blockHandler = "handleException")
    public String byResource() {
        return "按资源名称SentinelResource限流测试OK";
    }

    public String handleException(BlockException exception) {
        return "服务不可用@SentinelResource启动" + "\t" + "o(╥﹏╥)o";
    }

    @GetMapping("/rateLimit/{p1}")
    @SentinelResource(value = "doActionSentinelResource",
            blockHandler = "doActionBlockHandler",
            fallback = "doActionFallback")  //自定义降级处理方法
    public String doAction(@PathVariable("p1") Integer p1) {
        if (p1 == 0) {
            throw new RuntimeException("p1等于零直接异常");
        }
        return "doAction";
    }

    public String doActionBlockHandler(@PathVariable("p1") Integer p1, BlockException e) {
        return "sentinel配置自定义限流了";
    }

    public String doActionFallback(@PathVariable("p1") Integer p1, Throwable e) {
        return "程序逻辑异常了" + "\t" + e.getMessage();
    }

    @GetMapping("/testHotKey")
    @SentinelResource(value = "testHotKey", blockHandler = "dealHandler_testHotKey")
    public String testHotKey(@RequestParam(value = "p1", required = false) String p1,
                             @RequestParam(value = "p2", required = false) String p2) {
        return "------testHotKey";
    }

    public String dealHandler_testHotKey(String p1, String p2, BlockException exception) {
        return "-----dealHandler_testHotKey";
    }


    @GetMapping(value = "/empower")
    public String requestSentinel4(){
        return "Sentinel授权规则";
    }

}


